package com.leetcode;

/**
 * 307. 区域和检索 - 数组可修改
 * 超时了
 */
public class Solution307 {

    class NumArray {

        private int[] nums;
        private int[] sums;
        private int size;

        public NumArray(int[] nums) {
            this.nums = nums;
            this.size = nums.length;
            this.sums = new int[this.size + 1];
            this.sums[0] = this.nums[0];
            for (int i = 1; i < this.size; i++) {
                this.sums[i] = this.sums[i - 1] + this.nums[i];
            }
        }

        public void update(int index, int val) {
            this.checkIndex(index);
            int sub = val - this.nums[index];
            this.nums[index] = val;
            for (int i = index; i < this.size; i++) {
                this.sums[i] += sub;
            }
        }

        public int sumRange(int left, int right) {
            this.checkIndex(left);
            this.checkIndex(right);
            if (left > right) {
                throw new IllegalArgumentException("left > right");
            }
            return left > 0 ? this.sums[right] - this.sums[left - 1] : this.sums[right];
        }

        private void checkIndex(int index) {
            if (index < 0 || index >= this.size) {
                throw new IllegalArgumentException("out of index");
            }
        }
    }

    public static void main(String[] args) {

    }

}
